#include "client.h"
#include "config/applicationconfiguration.h"
#include "net/poller.h"

Client::Client()
{
}

void Client::startPolling(){

    QList<Host> &remoteHosts = ApplicationConfiguration::remoteHosts;

    // start polling thread to every server read from configuration file
    for(int i = 0; i < remoteHosts.size(); ++i){

        QTcpSocket* serverConnection = new QTcpSocket;
        Poller *worker = new Poller(serverConnection, remoteHosts[i].getPort(), remoteHosts[i].getHostName());
        QThread *workerThread = new QThread(this);

        // save connection when it is established with server
        connect(serverConnection, SIGNAL(connected()), this, SLOT(connectionEstablished()));

        // finish polling thread when connection is established
        connect(serverConnection, SIGNAL(connected()), workerThread, SLOT(quit()));

        // remove server socket from server sockets list
        connect(serverConnection, SIGNAL(disconnected()), this, SLOT(connectionBroken()));

        // delete connection when server breaks connection
        connect(serverConnection, SIGNAL(disconnected()), serverConnection, SLOT(deleteLater()));

        // delete worker object when thread finishes
        connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));

        // connect start of thread with polling server
        connect(workerThread, SIGNAL(started()), worker, SLOT(pollServer()));

        worker->moveToThread(workerThread);
        serverConnection->moveToThread(workerThread);

        // start thread and polling server
        workerThread->start();

    }

}

void Client::connectionEstablished(){

    QTcpSocket* sender = (QTcpSocket*)QObject::sender();

    // add server socket after establishing connection
    serverConnections.push_back(sender);

    emit addServer(sender->peerAddress().toString(), sender->peerPort());
}


void Client::connectionBroken(){

    // remove server socket after disconnecting
    serverConnections.removeOne((QTcpSocket*)QObject::sender());

    emit removeServer(((QTcpSocket*)QObject::sender())->peerAddress().toString());

}

void Client::broadcastMessage(QString msg){

    QByteArray block = msg.toUtf8();

    for(int i = 0; i < serverConnections.size(); ++i){
        serverConnections.at(i)->write(block);
        serverConnections.at(i)->waitForBytesWritten();
    }

}
